// task_withdraw_record_page_vm.dart
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:sjx/repository/model/task_withdraw_record_model.dart';
import 'package:sjx/repository/sjx_api.dart';

import '../../../../common_ui/refresh_error_alert.dart';


class TaskWithdrawRecordPageViewModel with ChangeNotifier {
  int _pageNum = 1;
  final int _pageSize = 20;
  bool _isLoading = false;
  bool _hasMore = true;

  List<TaskWithdrawRecordModel> _monthList = [];
  LoadErrorType? _errorType;
  String _errorMessage = '';

  // Getters
  bool get isLoading => _isLoading;
  bool get hasMore => _hasMore;
  List<TaskWithdrawRecordModel> get monthList => _monthList;
  LoadErrorType? get errorType => _errorType;
  String get errorMessage => _errorMessage;

  Future<void> loadData({bool isRefresh = false}) async {
    if (_isLoading) return;

    _isLoading = true;
    _errorType = null;
    _errorMessage = '';

    if (isRefresh) {
      _pageNum = 1;
      _hasMore = true;
    }

    notifyListeners();

    try {
      final Response response = await SJXApi.instance().userExchanges({'page': _pageNum, 'size': _pageSize, 'exchangeType': '提现'});

      final List<dynamic> records = response.data['userExchangeInfos'] ?? [];

      if (isRefresh) {
        _monthList.clear();
      }

      for (final record in records) {
        final model = TaskWithdrawRecordModel.fromJson(record);
        _monthList.add(model);
      }

      _hasMore = records.length >= _pageSize;
      if (!isRefresh && _hasMore) {
        _pageNum++;
      }

      // 如果没有数据且不是加载更多，显示无数据状态
      if (isRefresh && _monthList.isEmpty) {
        _errorType = LoadErrorType.noData;
      }

    } catch (e) {
      _errorType = LoadErrorType.noNetwork;
      _errorMessage = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  void refresh() {
    loadData(isRefresh: true);
  }

  void loadMore() {
    if (_hasMore && !_isLoading) {
      loadData(isRefresh: false);
    }
  }


  // 重置状态
  void reset() {
    _pageNum = 1;
    _hasMore = true;
    _monthList.clear();
    _errorType = null;
    _errorMessage = '';
    notifyListeners();
  }
}